<template>
  <div class="config-version-container">
    <a-card class="box-card">
      <div slot="title" class="card-header">
        <span>产品版本配置</span>
      </div>
      
      <div class="version-content" v-if="!loading">
        <!-- 审核版本配置部分 -->
        <div class="section">
          <h3>审核版本配置</h3>
          
          <div class="current-version">
            <span class="label">当前审核版本：</span>
            <span class="value">{{ currentVersion }}</span>
          </div>
          
          <div class="version-description">
            <p>版本说明：</p>
            <ul>
              <li><strong>V1版本</strong>：当设置为V1时，V1接口只返回用户创建的产品，V2接口返回正常逻辑</li>
              <li><strong>V2版本</strong>：当设置为V2时，V2接口只返回用户创建的产品，V1接口返回正常逻辑</li>
            </ul>
          </div>
          
          <div class="switch-version">
            <span class="label">切换审核版本：</span>
            <a-radio-group v-model="selectedVersion" size="large" button-style="solid">
              <a-radio-button value="V1">V1版本</a-radio-button>
              <a-radio-button value="V2">V2版本</a-radio-button>
            </a-radio-group>
            
            <a-button 
              type="primary" 
              :disabled="selectedVersion === currentVersion"
              @click="handleSwitchVersion"
              class="switch-btn"
              :loading="switching"
            >
              确认切换
            </a-button>
          </div>
        </div>
        
        <a-divider />
        
        <!-- 客户端版本限制配置部分 -->
        <div class="section">
          <h3>线上版本配置</h3>
          
          <div class="current-version">
            <span class="label">当前线上版本：</span>
            <span class="value">{{ onlineVersion }}</span>
          </div>
          
          <div class="version-description">
            <p>说明：</p>
            <ul>
              <li><strong>线上版本规则</strong>：高于线上版本的客户端只能看到用户创建的产品，低于或等于线上版本的客户端可以看到所有产品</li>
              <li><strong>版本示例</strong>：线上版本为"1.1.4"，客户端版本为"1.1.5"(送审版本)时只显示用户创建的产品，客户端版本 &lt;= 1.1.4 时显示所有产品</li>
              <li><strong>适用接口</strong>：使用 /products/client-version?clientVersion=x.x.x 接口调用时生效</li>
            </ul>
          </div>
          
          <div class="version-limit-input">
            <span class="label">设置线上版本：</span>
            <a-input-group compact>
              <a-input
                v-model="inputOnlineVersion"
                placeholder="输入版本号，如 1.1.4"
                style="width: 200px"
                :maxLength="20"
              />
              <a-button 
                type="primary" 
                :disabled="!isValidVersion(inputOnlineVersion) || inputOnlineVersion === onlineVersion"
                @click="handleSetOnlineVersion"
                :loading="settingOnlineVersion"
              >
                确认设置
              </a-button>
            </a-input-group>
            <div v-if="onlineVersionError" class="error-message">{{ onlineVersionError }}</div>
          </div>
        </div>
      </div>
      
      <div v-else class="loading-container">
        <a-spin tip="加载中..." />
      </div>
    </a-card>
  </div>
</template>

<script>
import { fetchProductVersion, switchProductVersion, fetchOnlineVersion, setOnlineVersion } from '@/api/product';

export default {
  name: 'ConfigVersion',
  data() {
    return {
      loading: false,
      switching: false,
      settingOnlineVersion: false,
      currentVersion: 'V1',
      selectedVersion: 'V1',
      onlineVersion: '1.1.4',
      inputOnlineVersion: '',
      onlineVersionError: ''
    };
  },
  created() {
    this.fetchAllSettings();
  },
  methods: {
    // 获取所有配置设置
    async fetchAllSettings() {
      this.loading = true;
      try {
        // 并行请求两个配置
        const [versionRes, onlineVersionRes] = await Promise.all([
          this.fetchCurrentVersion(),
          this.fetchOnlineVersion()
        ]);
        
        if (versionRes && versionRes.productVersion) {
          this.currentVersion = versionRes.productVersion;
          this.selectedVersion = versionRes.productVersion;
        }
        
        if (onlineVersionRes && onlineVersionRes.onlineVersion) {
          this.onlineVersion = onlineVersionRes.onlineVersion;
          this.inputOnlineVersion = onlineVersionRes.onlineVersion;
        }
      } catch (error) {
        console.error('获取配置失败:', error);
        this.$message.error('获取配置失败');
      } finally {
        this.loading = false;
      }
    },
    
    // 获取当前审核版本
    async fetchCurrentVersion() {
      try {
        return await fetchProductVersion();
      } catch (error) {
        console.error('获取产品版本失败:', error);
        return null;
      }
    },
    
    // 获取当前线上版本
    async fetchOnlineVersion() {
      try {
        return await fetchOnlineVersion();
      } catch (error) {
        console.error('获取线上版本失败:', error);
        return null;
      }
    },
    
    // 切换审核版本
    async handleSwitchVersion() {
      if (this.selectedVersion === this.currentVersion) {
        return;
      }
      
      this.switching = true;
      try {
        const res = await switchProductVersion(this.selectedVersion);
        if (res && res.productVersion) {
          this.currentVersion = res.productVersion;
          this.$message.success(`已成功切换到${res.productVersion}版本`);
        }
      } catch (error) {
        console.error('切换版本失败:', error);
        this.$message.error('切换版本失败');
        // 重置选择
        this.selectedVersion = this.currentVersion;
      } finally {
        this.switching = false;
      }
    },
    
    // 设置线上版本
    async handleSetOnlineVersion() {
      if (!this.isValidVersion(this.inputOnlineVersion) || this.inputOnlineVersion === this.onlineVersion) {
        return;
      }
      
      this.settingOnlineVersion = true;
      this.onlineVersionError = '';
      
      try {
        const res = await setOnlineVersion(this.inputOnlineVersion);
        if (res && res.onlineVersion) {
          this.onlineVersion = res.onlineVersion;
          this.$message.success(`已成功设置线上版本为 ${res.onlineVersion}`);
        }
      } catch (error) {
        console.error('设置线上版本失败:', error);
        this.$message.error('设置线上版本失败');
        this.onlineVersionError = error.message || '设置失败，请确认输入格式正确';
        // 恢复原始值
        this.inputOnlineVersion = this.onlineVersion;
      } finally {
        this.settingOnlineVersion = false;
      }
    },
    
    // 验证版本号格式
    isValidVersion(version) {
      // 简单版本号格式验证：x.y.z（数字和点）
      return /^\d+\.\d+\.\d+$/.test(version);
    }
  }
};
</script>

<style scoped>
.config-version-container {
  padding: 20px;
}

.card-header {
  font-size: 18px;
  font-weight: bold;
}

.version-content {
  min-height: 300px;
}

.loading-container {
  display: flex;
  justify-content: center;
  align-items: center;
  min-height: 300px;
}

.section {
  margin-bottom: 30px;
}

.section h3 {
  margin-bottom: 20px;
  font-size: 16px;
  font-weight: bold;
  color: #333;
}

.current-version {
  margin-bottom: 20px;
  font-size: 16px;
}

.current-version .value {
  font-weight: bold;
  font-size: 18px;
  color: #1890ff;
}

.version-description {
  margin-bottom: 20px;
  color: rgba(0, 0, 0, 0.65);
}

.version-description p {
  font-weight: bold;
  margin-bottom: 10px;
}

.switch-version {
  margin-top: 20px;
  display: flex;
  align-items: center;
}

.switch-version .label {
  margin-right: 15px;
  font-size: 16px;
}

.switch-btn {
  margin-left: 20px;
}

.version-limit-input {
  margin-top: 20px;
}

.version-limit-input .label {
  display: block;
  margin-bottom: 10px;
  font-size: 16px;
}

.error-message {
  color: #f5222d;
  margin-top: 5px;
  font-size: 14px;
}
</style>
